package com.kgc.cart.controller;

import com.kgc.entity.TbItem;
import com.kgc.service.ItemService;
import com.kgc.utils.CookieUtils;
import com.kgc.utils.ItripResult;
import com.kgc.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@Controller
public class CartController {

    @Autowired
    private ItemService itemService;
    @Value("${CART}")
    private String CART;


    private List<TbItem> getCartList(HttpServletRequest request){
        //购物车
        List<TbItem> list=null;
        //1.从cookie中得到一个购物车
        String cartCookie= CookieUtils.getCookieValue(request,CART,true);
        //2.判断cookie是否有购物车
        if(!StringUtils.isEmpty(cartCookie)){
            list= JsonUtils.jsonToList(cartCookie,TbItem.class);
        }else{
            list=new ArrayList<>();
        }
        return list;
    }

    @RequestMapping("/cart/cart")
    public String cart(Model model, HttpServletRequest request){
        //从cookie中得到购物车
        List<TbItem> list=getCartList(request);
        model.addAttribute("cartList",list);
        return "cart";
    }
    @RequestMapping("/cart/add/{itemId}")
    public String toOrder(@PathVariable("itemId")Long id,
                          @RequestParam(value = "num",required = false,defaultValue = "1") int num, HttpServletRequest request, HttpServletResponse response){
        List<TbItem> list = getCartList(request);
        TbItem item=null;
        boolean flag=false;
        if (list.size()>0){
            for(int i=0;i<list.size();i++){
                if(id.equals(list.get(i).getId())){
                    item=list.get(i);
                    item.setNum(item.getNum()+num);
                    flag=true;
                    break;
                }
            }
        }
        if(flag==false){//向list增加一个新商品
            item=itemService.findById(id);
            String[] images=item.getImage().split(",");
            item.setImage(images[0]);
            item.setNum(num);
            list.add(item);
        }
        String jsonString=JsonUtils.objectToJson(list);
        CookieUtils.setCookie(request,response,CART,jsonString,86400,true);
        //4.如果有购物车,判断以前是否买过这个商品，找到后加数量
        return "cartSuccess";
    }

    @ResponseBody
    @RequestMapping("/cart/update/num/{itemId}/{num}")
    public ItripResult cartUpdate(HttpServletRequest request,
                                 HttpServletResponse response ,@PathVariable("itemId")Long itemId,@PathVariable("num")int num){
        List<TbItem> cart = getCartList(request);
        TbItem item= null;
        for (int i = 0; i < cart.size(); i++) {
            if (cart.get(i).equals(itemId)){
                item=cart.get(i);
                item.setNum(num);
                break;
            }
        }
        String jsonString = JsonUtils.objectToJson(cart);
        CookieUtils.setCookie(request,response,CART,jsonString,86400,true);
        return ItripResult.ok();
    }

    @RequestMapping("/cart/delete/{itemId}")
    public String deleteCartItem(@PathVariable("itemId")Long itemId,
                                 HttpServletRequest request,
                                 HttpServletResponse response){
        //1.得到cart
        List<TbItem> list=getCartList(request);
        TbItem item=null;
        for(int i=0;i<list.size();i++){
            TbItem item1=list.get(i);
            if(item1.getId().equals(itemId)){
                list.remove(item1);
            }
        }
        String jsonString=JsonUtils.objectToJson(list);
        CookieUtils.setCookie(request,response,"CART",jsonString,86400,true);
        return "redirect:/cart/cart";
    }

}
